<template>
  <div>
    <el-row class="setBox">
      <el-button
        v-if="isShowUpdate"
        type="primary"
        icon="iconfont iconshezhi"
        @click="updateSet()"
        class="commonBut saveBtn funComBut"
      >
        <span class="opetareText">等级配置</span>
      </el-button>
    </el-row>
    <el-row>
      <el-table
        :data="reverseSetList"
        style="width: 100%; margin-top: 24px; border: 1px solid #dfe6ec"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        stripe
      >
        <el-table-column
          label="序号"
          type="index"
          width="88"
          align="left"
        ></el-table-column>
        <el-table-column
          prop="gradeLevel"
          label="等级"
          min-width="230"
          align="center"
        ></el-table-column>
        <el-table-column label="分数区间" min-width="230" align="center">
          <template slot-scope="scope">
            <span
              >{{ scope.row.startScore
              }}{{
                scope.$index === setForm.setList.length - 1 ? '≤' : '＜'
              }}分数≤{{ scope.row.endScore }}</span
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="left" fixed="right">
          <template slot-scope="scope">
            <el-link
              v-if="isShowUpdate"
              @click="updateSet(scope.row)"
              style="font-size: 14px; color: #409eff"
              >修改</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-dialog
      title="等级配置"
      :visible.sync="levelSetVisible"
      :close-on-click-modal="false"
      @closed="closeDialog"
      width="640px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <el-form :model="setForm" ref="formRef" :rules="rules">
        <el-row style="margin-bottom: 16px" class="title">
          <span class="titleLevel">等级</span>
          <span class="titleScore">分数区间（分数精确到小数点后两位）</span>
          <span class="titleAction"></span>
        </el-row>
        <el-row
          v-for="(item, index) in setForm.setList"
          :key="index"
          class="flexBox"
        >
          <el-form-item
            :prop="'setList.' + index + '.gradeLevel'"
            class="titleLevel"
            :rules="rules.gradeLevel"
          >
            <el-input v-model="item.gradeLevel"></el-input>
          </el-form-item>
          <div class="titleScore">
            <el-form-item class="subLevel">
              <el-input disabled="true" v-model="item.startScore"></el-input>
            </el-form-item>
            <span class="score">{{ index === 0 ? '≤' : '&lt;' }} 分数 ≤</span>
            <el-form-item
              :prop="'setList.' + index + '.endScore'"
              class="subLevel"
              :rules="rules.endScore"
            >
              <el-input
                @input="changeScore(index)"
                v-model="item.endScore"
              ></el-input>
            </el-form-item>
          </div>
          <el-link
            v-if="index !== 0"
            type="primary"
            class="titleAction"
            @click="delLevel(index)"
            >删除</el-link
          >
          <el-link v-else type="primary" class="titleAction"></el-link>
        </el-row>
      </el-form>
      <el-row @click.native="addLevel" class="addLevel">
        <span style="font-size: 25px">+</span>
        <span style="position: relative; top: -4px">添加等级</span>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialog" class="cancel">取消</el-button>
        <el-button
          type="primary"
          @click.native="saveSet('formRef')"
          v-sdc
          :loading="isAdd"
          class="save"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'levelDetail',
  props: {
    scoreDimType: {
      type: String,
      default: '',
    },
  },
  watch: {
    scoreDimType(newValue, oldValue) {
      this.getLevelSet(this.scoreDimType)
    },
  },
  data() {
    var validateScore = (rule, value, callback) => {
      this.isAllowAdd = false
      let currentIndex = rule.field.split('.')[1] * 1
      let startScore = 0
      let endScore = 100
      if (currentIndex > 0) {
        startScore = this.setForm.setList[currentIndex - 1].endScore * 1
      }
      if (currentIndex < this.setForm.setList.length - 1) {
        endScore = this.setForm.setList[currentIndex + 1].endScore * 1
      }
      let reg = /^(([1-9]\d*)(\.\d{1,2})?|0\.([1-9]|\d[1-9])|0)$/
      if (!reg.test(value)) {
        callback(new Error('支持整数或两位小数'))
      } else if (value * 1 > 100) {
        callback(new Error('最大分数为100'))
      } else if (value * 1 <= startScore && currentIndex != 0) {
        callback(new Error('应大于上一级最高分'))
      } else if (
        endScore &&
        value * 1 >= endScore &&
        currentIndex < this.setForm.setList.length - 1
      ) {
        callback(new Error('应小于下一级最高分'))
      } else {
        this.isAllowAdd = true
        callback()
      }
    }
    var checkLevel = (rule, value, callback) => {
      let reg = /^[A-Z][\+|\-]{0,1}$/
      let flag = false
      let index = this.setForm.setList.findIndex((v) => v.gradeLevel === value)
      this.setForm.setList.forEach((v, i) => {
        if (i != index && v.gradeLevel === value) {
          flag = true
        }
      })
      if (!reg.test(value)) {
        callback(new Error('请输入A-Z和+ -'))
      } else if (flag) {
        callback(new Error('请输入不同的等级'))
      } else {
        callback()
      }
    }
    return {
      levelSetVisible: false,
      isAllowAdd: true, //是否允许添加
      isAdd: false,
      copyList: [],
      // 表单内容
      setForm: {
        setList: [],
      },
      // 验证规则
      rules: {
        gradeLevel: [
          { required: true, message: '请输入等级', trigger: 'blur' },
          { validator: checkLevel, trigger: 'blur' },
        ],
        endScore: [
          {
            required: true,
            message: '分数不能为空',
            trigger: 'blur',
          },
          { validator: validateScore, trigger: 'blur' },
        ],
      },
      updateStatus: false,
      isShowAdd: '',
      isShowSave: '',
      isShowUpdate: '',
    }
  },
  computed: {
    reverseSetList() {
      const reverseList = JSON.parse(JSON.stringify(this.copyList))
      return reverseList.reverse()
    },
  },
  async created() {
    this.getLevelSet(this.scoreDimType)
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('levelSet:update') > -1
  },
  methods: {
    // 获取评级设置
    getLevelSet(type) {
      this.axios({
        method: 'post',
        url: '/api-ps/creditLevel/expand/getCreditLevelList',
        data: {
          type,
        },
      })
        .then((response) => {
          if (response.data.hasError) {
            this.$message.error(response.data.errorMsg)
          } else {
            const listData = response.data.result.reverse()
            const setList = []
            listData.forEach((v, i) => {
              setList[i] = {}
              setList[i].gradeLevel = v.gradeLevel
              setList[i].startScore = v.startScore
              setList[i].endScore = v.endScore
            })
            this.setForm.setList = JSON.parse(JSON.stringify(setList))
            this.copyList = JSON.parse(JSON.stringify(setList))
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 新增/修改等级配置
    updateSet() {
      this.levelSetVisible = true
    },
    // 添加等级
    addLevel() {
      if (
        this.setForm.setList.length &&
        ((!this.setForm.setList[this.setForm.setList.length - 1].endScore &&
          this.setForm.setList[this.setForm.setList.length - 1].endScore !=
            0) ||
          !this.isAllowAdd ||
          this.setForm.setList[this.setForm.setList.length - 1].endScore * 1 >=
            100)
      ) {
        return
      } else {
        let addObj = {}
        addObj.gradeLevel = ''
        addObj.startScore = 0
        addObj.endScore = null
        if (this.setForm.setList.length > 0) {
          addObj.startScore =
            this.setForm.setList[this.setForm.setList.length - 1].endScore
          // ? this.setForm.setList[this.setForm.setList.length - 1]
          //       .endScore
          // : null;
        }
        this.setForm.setList.push(addObj)
      }
    },
    // 删除评级
    delLevel(index) {
      let updateList = JSON.parse(JSON.stringify(this.setForm.setList))
      updateList.splice(index, 1)
      if (index <= updateList.length - 1) {
        updateList[index].startScore = updateList[index - 1].endScore
      }
      this.setForm.setList = updateList
    },
    // 修改分数
    changeScore(index) {
      if (index < this.setForm.setList.length - 1) {
        this.setForm.setList[index * 1 + 1].startScore =
          this.setForm.setList[index].endScore
      }
    },
    // 表单提交
    saveSet(formName) {
      this.isAdd = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.setForm.setList.length > 0) {
            this.axios({
              method: 'post',
              url: '/api-ps/creditLevel/expand/save',
              data: {
                type: this.scoreDimType,
                creditLevels: JSON.stringify(this.setForm.setList),
              },
            })
              .then((response) => {
                if (response.data.hasError) {
                  this.$message.error(response.data.errorMsg)
                } else {
                  this.$message.success('保存成功')
                  this.isAdd = false
                  this.levelSetVisible = false
                  this.getLevelSet(this.scoreDimType)
                }
              })
              .catch((error) => {
                if (error.response) {
                  this.$message.error(error.response.data)
                }
              })
          } else {
            this.$message.error('请先添加等级区间')
            this.isAdd = false
            return false
          }
        } else {
          this.$message.error('请按照提示规则输入内容!')
          this.isAdd = false
          return false
        }
      })
    },
    // 关闭dialog
    closeDialog() {
      this.levelSetVisible = false
      this.$refs['formRef'].resetFields()
      this.setForm.setList = JSON.parse(JSON.stringify(this.copyList))
    },
  },
}
</script>

<style scoped lang="less">
/deep/.el-input {
  width: 100%;
  height: 36px;
  input {
    text-align: center;
  }
}

/deep/ .el-dialog__body {
  max-height: 500px;
}
.titleLevel {
  display: inline-block;
  width: 120px;
  margin-right: 22px;
  text-align: center;
}
.subLevel {
  display: inline-block;
  width: calc((100% - 74px) / 2);
}
.titleScore {
  display: inline-block;
  width: 400px;
  text-align: center;
  margin-right: 12px;
}
.titleAction {
  display: inline-block;
  width: 30px;
  position: relative;
  right: 0;
  text-align: center;
}
.titleAction:hover {
  cursor: pointer;
}
.score {
  display: inline-block;
  width: 64px;
  text-align: center;
}
.addLevel {
  height: 32px;
  text-align: center;
  line-height: 30px;
  font-size: 14px;
  color: #a3a3a3;
  border: 1px dashed #dee5f4;
}
.addLevel:hover {
  cursor: pointer;
  color: #409eff;
  border-color: #409eff;
}
</style>
